package com.eascs.workflow.sys.dao.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import org.apache.commons.lang3.StringUtils;

import com.eascs.app.dao.DefaultIdBuilder;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.workflow.common.dao.BaseDao;
import com.eascs.workflow.common.entity.sys.SysResources;
import com.eascs.workflow.common.entity.sys.SysResourcesFormEntity;
import com.eascs.workflow.common.entity.sys.SysRole;
import com.eascs.workflow.sys.dao.SysResourcesDao;

@Repository
public class SysResourcesDaoImpl extends BaseDao implements SysResourcesDao{
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
     * 根据角色 查询资源权限
     * @param 
     * @return
     */
    public List<SysResources> selectResourcesByRoles(List<SysRole> roles){
    	if(roles==null || roles.size()==0){
			logger.info("error,method:SysUserDaoImpl.selectResourcesByRoles必要参数不能为空!");
			return null;
		}
    	List<String> rids=new ArrayList<String>();
    	for (SysRole sysRole : roles) {
    		rids.add(sysRole.getId());
		}
    	String str="('" + StringUtils.join(rids,"','") + "')";
    	StringBuffer sql=new StringBuffer();
    	sql.append(" SELECT res.id,res.resource_name,res.resource_code,res.resource_type,res.resDefault,res.resource_url,res.description,res.parent_id,res.sort,res.creator,res.updator,res.create_time,res.update_time");
    	sql.append(" FROM o2o_act_role AS role");
    	sql.append(" LEFT JOIN o2o_act_role_resources AS rm ON role.id = rm.role_id");
    	sql.append(" LEFT JOIN o2o_act_resources AS res ON rm.resources_id = res.id");
    	sql.append(" WHERE role.id IN " + str +" AND res.resDefault='N' GROUP BY rm.resources_id");
        List<SysResources> list = workflowJdbcSession.findEntitys(sql.toString(), SysResources.class,new Object[]{});
        return list;
    }

	@Override
	public List<SysResources> selectResourcesList() {
		StringBuffer sql=new StringBuffer();
    	sql.append(" SELECT res.id,res.resource_name,res.resource_code,res.resource_type,res.resDefault,res.resource_url,res.description,res.parent_id,res.sort,res.creator,res.updator,res.create_time,res.update_time");
    	sql.append(" FROM o2o_act_resources AS res");
    	sql.append(" ORDER BY res.parent_id ASC,res.sort ASC");
        List<SysResources> list = workflowJdbcSession.findEntitys(sql.toString(), SysResources.class, new Object[] {});
        return list;
	}

	@Override
	public int insertResources(SysResources param) {
		param.setId(DefaultIdBuilder.build());
		StringBuffer sql=new StringBuffer();
		sql.append("insert into o2o_act_resources(resource_url,creator,create_time,resource_code,resDefault,resource_type,description,sort,update_time,parent_id,updator,resource_name,id) values (?,?,?,?,?,?,?,?,?,?,?,?,?)");
		return workflowJdbcSession.execute(sql.toString(), new Object[]{
				param.getResourceUrl(),param.getCreator(),param.getCreateTime(),param.getResourceCode(),param.getResourceDefault(),
				param.getResourceType(),param.getDescription(),param.getSort(),param.getUpdateTime(),param.getParentId(),
				param.getUpdator(),param.getResourceName(),param.getId()
		});
	}

	@Override
	public int updateResources(SysResources sysResources) {
		StringBuffer sql=new StringBuffer();
    	sql.append(" update o2o_act_resources set resource_url=?,creator=?,update_time=?,resource_code=?,parent_id=?,resource_type=?,resDefault=?,description=?,updator=?,sort=?,resource_name=? where id=?");
    	return workflowJdbcSession.execute(sql.toString(), new Object[]{sysResources.getResourceUrl(),sysResources.getCreator(),sysResources.getUpdateTime(),sysResources.getResourceCode(),sysResources.getParentId(),sysResources.getResourceType(),sysResources.getResourceDefault(),sysResources.getDescription(),sysResources.getUpdator(),sysResources.getSort(),sysResources.getResourceName(),sysResources.getId()});
	}

	@Override
	public int deleteResources(SysResources sysResources) {
		return workflowJdbcSession.deleteByIdWithEntity(sysResources);
	}

	@Override
	public List<SysResources> selectDefaultResourcesList() {
		StringBuffer sql=new StringBuffer();
    	sql.append(" SELECT res.id,res.resource_name,res.resource_code,res.resource_type,res.resDefault,res.resource_url,res.description,res.parent_id,res.sort,res.creator,res.updator,res.create_time,res.update_time");
    	sql.append(" FROM o2o_act_resources AS res WHERE res.resDefault='Y'");
        List<SysResources> list = workflowJdbcSession.findEntitys(sql.toString(), SysResources.class, new Object[] {});
        return list;
	}

	@Override
	public List<SysResources> selectUnDefaultResourcesList() {
		StringBuffer sql=new StringBuffer();
    	sql.append(" SELECT res.id,res.resource_name,res.resource_code,res.resource_type,res.resDefault,res.resource_url,res.description,res.parent_id,res.sort,res.creator,res.updator,res.create_time,res.update_time");
    	sql.append(" FROM o2o_act_resources AS res WHERE res.resDefault='N'");
        List<SysResources> list = workflowJdbcSession.findEntitys(sql.toString(), SysResources.class, new Object[] {});
        return list;
	}

	@Override
	public List<SysResources> selectResourcesListByCode(String code) {
		StringBuffer sql=new StringBuffer();
    	sql.append(" SELECT res.id,res.resource_name,res.resource_code,res.resource_type,res.resDefault,res.resource_url,res.description,res.parent_id,res.sort,res.creator,res.updator,res.create_time,res.update_time");
    	sql.append(" FROM o2o_act_resources AS res");
    	sql.append(" WHERE res.resource_code=?");
    	 List<SysResources> list = workflowJdbcSession.findEntitys(sql.toString(), SysResources.class, new Object[] {code});
         return list;
	}

	@Override
	public SysResources getResourcesByIds(String ids) {
		String sql = "SELECT * FROM o2o_act_resources WHERE id = ?";
		return super.findEntity(sql, SysResources.class, new Object[] { ids });
	}

	/**
	 * 分页查询-已分配角色清单(根据资源id查询)
	 */
	@Override
	public PageResult<Object[]> findRolePageByResId(SysResourcesFormEntity entity) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, entity.getPageSize(), entity.getPageIndex());
		StringBuffer querySql = new StringBuffer();
		
		querySql.append("  SELECT res.id AS resId,role.role_code,role.role_name  ");
		querySql.append("  FROM o2o_act_resources AS res  ");
		querySql.append("  LEFT JOIN o2o_act_role_resources AS rm ON rm.resources_id = res.id  ");
		querySql.append("  LEFT JOIN o2o_act_role AS role ON role.id = rm.role_id  ");
		querySql.append("  WHERE 1=1 ");
		if (!StringUtil.isEmpty(entity.getId())) {
			querySql.append(" AND res.id= ?");
			sqlPageQuery.addParam(entity.getId());
		}
		if (!StringUtil.isEmpty(entity.getRoleCode())) {
			querySql.append(" AND role.role_code= ?");
			sqlPageQuery.addParam(entity.getRoleCode());
		}
		if (!StringUtil.isEmpty(entity.getRoleName())) {
			querySql.append(" AND role.role_name like ?");
			sqlPageQuery.addLikeParam(entity.getRoleName());
		}
		querySql.append(" ORDER BY CONVERT(role.role_name USING gbk) ASC ");
		
		sqlPageQuery.setQuerySql(querySql.toString());
		return this.findDataWithPage(sqlPageQuery);
	}

	/**
	 * 分页查询-已分配人员清单(根据资源id查询)
	 * 去重(group by 人员工号)
	 */
	@Override
	public PageResult<Object[]> findEmployeePageByResId(SysResourcesFormEntity entity) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, entity.getPageSize(), entity.getPageIndex());
		StringBuffer querySql = new StringBuffer();
		
		querySql.append("  SELECT rre.resources_id,oru.org_name,emp.employee_code,emp.employee_namecn  ");
		querySql.append("  FROM o2o_employee AS emp  ");
		querySql.append("  LEFT JOIN act_org_role_user AS oru ON oru.user_no=emp.employee_no AND oru.is_remove=0  ");
		querySql.append("  LEFT JOIN o2o_act_role_resources AS rre ON rre.role_id=oru.role_id  ");
		querySql.append("  WHERE 1=1 ");
		if (!StringUtil.isEmpty(entity.getId())) {
			querySql.append(" AND rre.resources_id= ?");
			sqlPageQuery.addParam(entity.getId());
		}
		if (!StringUtil.isEmpty(entity.getOrgName())) {
			querySql.append(" AND oru.org_name like ?");
			sqlPageQuery.addLikeParam(entity.getOrgName());
		}
		if (!StringUtil.isEmpty(entity.getEmployeeCode())) {
			querySql.append(" AND emp.employee_code= ?");
			sqlPageQuery.addParam(entity.getEmployeeCode());
		}
		if (!StringUtil.isEmpty(entity.getEmployeeNamecn())) {
			querySql.append(" AND emp.employee_namecn like ?");
			sqlPageQuery.addLikeParam(entity.getEmployeeNamecn());
		}
		querySql.append(" GROUP BY emp.employee_code ");//分组查询--去重(group by 人员工号)
		querySql.append(" ORDER BY CONVERT(oru.org_name USING gbk) ASC ");
		
		sqlPageQuery.setQuerySql(querySql.toString());
		return this.findDataWithPage(sqlPageQuery);
	}

}
